<!--
 *Author：jxx
 *Contact：283591387@qq.com
 *业务请在@/extension/wms/wms.huo/shipment.jsx或shipment.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://v3.volcore.xyz/docs/view-grid、https://v3.volcore.xyz/docs/web
 -->
<template>
    <view-grid ref="grid"
               :columns="columns"
               :detail="detail"
               :details="details"
               :editFormFields="editFormFields"
               :editFormOptions="editFormOptions"
               :searchFormFields="searchFormFields"
               :searchFormOptions="searchFormOptions"
               :table="table"
               :extend="extend"
               :onInit="onInit"
               :onInited="onInited"
               :searchBefore="searchBefore"
               :searchAfter="searchAfter"
               :addBefore="addBefore"
               :addAfter="addAfter"
               :updateBefore="updateBefore"
               :rowClick="rowClick"
               :modelOpenBefore="modelOpenBefore"
               :modelOpenAfter="modelOpenAfter">
        <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
        <template #gridHeader>
        </template>
    </view-grid>
</template>
<script setup lang="jsx">
    import extend from "@/extension/wms/wms.huo/shipment.jsx";
    import viewOptions from './shipment/options.js'
    import { ref, reactive, getCurrentInstance, watch, onMounted } from "vue";
    import { pushMessage } from '@/views/index/messageBus.js'
    const grid = ref(null);
    const { proxy } = getCurrentInstance()
    //http请求，proxy.http.post/get
    const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())

    let gridRef;//对应[表.jsx]文件中this.使用方式一样
    const orderListData = ref([]); // 存储完整的订单数据（使用响应式ref）
    
    //生成对象属性初始化
    const onInit = async ($vm) => {
        gridRef = $vm;
        //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
        //更多属性见：https://v3.volcore.xyz/docs/view-grid
    }
    
    // 加载订单列表
    const loadOrderList = async () => {
        try {
            console.log('开始加载订单列表...');
            // 调用订单查询接口，获取完整的订单数据
            const res = await proxy.http.post('/api/so_order/getPageData', {
                page: 1,
                rows: 1000,
                sort: 'order_id',
                order: 'desc'
            });
            
            console.log('订单列表响应:', res);
            console.log('响应数据类型:', typeof res);
            console.log('res.status:', res?.status);
            console.log('res.rows:', res?.rows);
            console.log('res.data:', res?.data);
            
            // 兼容多种可能的返回格式（不依赖status判断，只要有rows就用）
            let rows = null;
            if (res) {
                rows = res.rows || res.data?.rows || res.data;
            }
            
            console.log('解析出的rows:', rows);
            
            if (rows && Array.isArray(rows) && rows.length > 0) {
                // 保存完整订单数据供后续使用
                orderListData.value = rows;
                console.log('已保存订单数据，数量:', orderListData.value.length);
                console.log('第一条订单示例:', orderListData.value[0]);
                console.log('第一条订单的所有字段:', Object.keys(orderListData.value[0]));
                
                // 生成下拉框数据（简化格式，只显示订单编号）
                const dropdownData = rows
                    .filter(o => o.ordernoas) // 只显示有订单编号的订单
                    .map(o => {
                        console.log(`订单 ${o.order_id}: ordernoas="${o.ordernoas}", order_name="${o.order_name}"`);
                        return {
                            key: o.ordernoas, // key 字段
                            value: o.ordernoas, // value 字段
                            text: o.ordernoas // text 字段，只显示订单编号
                        };
                    });
                
                console.log('下拉框数据，数量:', dropdownData.length);
                console.log('下拉框数据内容:', dropdownData);
                
                // 设置下拉框数据
                let foundField = false;
                editFormOptions.forEach((row, rowIndex) => {
                    row.forEach((field, fieldIndex) => {
                        console.log(`检查字段 [${rowIndex}][${fieldIndex}]:`, field.field, field.dataKey);
                        if (field.field === 'order_no' || field.dataKey === 'OrderList') {
                            field.data = dropdownData;
                            foundField = true;
                            console.log('已设置订单编号下拉框数据，位置:', rowIndex, fieldIndex);
                        }
                    });
                });
                
                if (!foundField) {
                    console.warn('未找到订单编号字段，无法设置下拉框数据');
                }
                
                // 同时尝试通过 gridRef 设置
                if (gridRef && gridRef.editFormOptions) {
                    gridRef.editFormOptions.forEach(row => {
                        row.forEach(field => {
                            if (field.field === 'order_no' || field.dataKey === 'OrderList') {
                                field.data = dropdownData;
                                console.log('通过gridRef设置了订单编号下拉框数据');
                            }
                        });
                    });
                }
            } else {
                console.warn('未获取到订单数据或数据格式不正确');
                console.warn('rows值:', rows);
            }
        } catch (error) {
            console.error('加载订单列表失败:', error);
        }
    }
    //生成对象属性初始化后,操作明细表配置用到
    const onInited = async () => {
    }
    const searchBefore = async (param) => {
        //界面查询前,可以给param.wheres添加查询参数
        //返回false，则不会执行查询
        return true;
    }
    const searchAfter = async (rows, result) => {
        return true;
    }
    const addBefore = async (formData) => {
        //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
        
        console.log('=== 发货保存前检查 ===');
        console.log('formData 完整结构:', JSON.stringify(formData, null, 2));
        console.log('formData 的所有键:', Object.keys(formData));
        
        // 获取实际数据对象（可能在mainData中）
        const data = formData.mainData || formData;
        console.log('实际使用的数据对象:', data);
        
        console.log('data.shipment_no:', data.shipment_no);
        console.log('data.order_no:', data.order_no);
        console.log('data.product_name:', data.product_name);
        console.log('data.Num:', data.Num, '(类型:', typeof data.Num, ')');
        console.log('data.Address:', data.Address, '(类型:', typeof data.Address, ')');
        console.log('data.unit_price:', data.unit_price, '(类型:', typeof data.unit_price, ')');
        console.log('data.total_amount:', data.total_amount, '(类型:', typeof data.total_amount, ')');
        console.log('data.company_id:', data.company_id);
        
        // ⚠️ 关键修复：disabled字段不会自动提交，必须手动添加
        // 确保数据在正确的位置
        if (formData.mainData) {
            // 如果数据在mainData中，强制设置这些字段的值
            // 因为disabled字段不会被表单自动提交，所以必须手动赋值
            const numValue = Number(editFormFields.Num);
            const addressValue = String(editFormFields.Address || '');
            const productNameValue = String(editFormFields.product_name || '');
            const unitPriceValue = Number(editFormFields.unit_price);
            const totalAmountValue = Number(editFormFields.total_amount);
            
            formData.mainData.Num = numValue;
            formData.mainData.Address = addressValue;
            formData.mainData.product_name = productNameValue;
            formData.mainData.unit_price = unitPriceValue;
            formData.mainData.total_amount = totalAmountValue;
            
            console.log('✅ 已强制从editFormFields同步disabled字段到mainData');
            console.log('  Num:', formData.mainData.Num, '(来源:', editFormFields.Num, ', 转换后:', numValue, ')');
            console.log('  Address:', formData.mainData.Address, '(来源:', editFormFields.Address, ', 转换后:', addressValue, ')');
            console.log('  product_name:', formData.mainData.product_name);
            console.log('  unit_price:', formData.mainData.unit_price);
            console.log('  total_amount:', formData.mainData.total_amount);
            console.log('同步后的mainData完整内容:', JSON.stringify(formData.mainData, null, 2));
        } else {
            // 如果数据直接在formData中，也要强制设置
            formData.Num = Number(editFormFields.Num);
            formData.Address = String(editFormFields.Address || '');
            formData.product_name = String(editFormFields.product_name || '');
            formData.unit_price = Number(editFormFields.unit_price);
            formData.total_amount = Number(editFormFields.total_amount);
            
            console.log('✅ 已强制从editFormFields同步disabled字段到formData');
            console.log('  Num:', formData.Num, '(来源:', editFormFields.Num, ')');
            console.log('  Address:', formData.Address, '(来源:', editFormFields.Address, ')');
        }
        
        // 验证发货编号是否已存在（确保唯一性）
        // 暂时禁用此验证，因为可能误判
        if (false && data.shipment_no) {
            try {
                console.log('检查发货编号是否重复:', data.shipment_no);
                const checkRes = await proxy.http.post('/api/shipment/getPageData', {
                    page: 1,
                    rows: 1,
                    wheres: [{ name: 'shipment_no', value: data.shipment_no }]
                });
                
                console.log('发货编号查询结果:', checkRes);
                console.log('查询到的记录数:', checkRes?.rows?.length);
                
                if (checkRes && checkRes.rows && checkRes.rows.length > 0) {
                    console.warn('发现重复的发货编号:', checkRes.rows);
                    proxy.$message.error('发货编号已存在，请重新生成');
                    return false;
                }
            } catch (error) {
                console.error('验证发货编号失败:', error);
            }
        }
        
        // 去掉id字段（新增时不应该传主键）
        if (formData.mainData && formData.mainData.id) {
            delete formData.mainData.id;
            console.log('✅ 已删除mainData中的id字段');
        }
        if (formData.id) {
            delete formData.id;
            console.log('✅ 已删除formData中的id字段');
        }
        
        // 确保必填字段不为空
        if (!data.Num || data.Num === '' || data.Num === 0) {
            console.warn('⚠️ 下单数量为空或0，当前值:', data.Num);
        }
        if (!data.Address || data.Address === '') {
            console.warn('⚠️ 地址为空，当前值:', data.Address);
        }
        
        console.log('最终准备保存的数据:', formData);
        return true;
    }
    const addAfter = async (result, formData) => {
        // 新建发货后写入消息面板（与SignalR互补）
        try {
            if (result && result.status) {
                const data = formData || {};
                const no = data.shipment_no || '-';
                const desc = `新发货单【${no}】已创建，订单：${data.order_no || '-'}，数量：${data.Num || '-'}，单价：${data.unit_price ?? '-'}，总金额：${data.total_amount ?? '-'}`;
                pushMessage({
                    title: '发货创建通知',
                    desc,
                    date: new Date().toLocaleString(),
                    type: '发货',
                    tag: 'primary',
                    route: { path: '/shipment', query: { shipment_no: no } }
                });
            }
        } catch (e) { console.warn('写入发货消息失败', e); }
        return true;
    }

    const updateBefore = async (formData) => {
        //编辑保存前formData为对象，包括明细表、删除行的Id
        
        // 禁止修改发货编号（发货编号在创建后不可修改）
        console.log('编辑保存的数据:', formData);
        return true;
    }
    const rowClick = ({ row, column, event }) => {
        //查询界面点击行事件
        // grid.value.toggleRowSelection(row); //单击行时选中当前行;
    }
    const modelOpenBefore = async (row) => {//弹出框打开前方法
        console.log('弹出框打开前...');
        return true;//返回false，不会打开弹出框
    }
    const modelOpenAfter = async (row) => {
        //弹出框打开后方法,设置表单默认值,按钮操作等
        console.log('弹出框打开后，准备加载订单列表...');
        // 在弹出框打开后加载订单列表
        await loadOrderList();
        console.log('订单列表加载完成，当前数据量:', orderListData.value.length);
        
        // 如果是新增操作，自动生成发货编号
        if (!row || !row.id) {
            await generateShipmentNo();
        }

        // 监听来自订单页的反填事件
        const handler = (e) => {
            const data = e.detail || {};
            editFormFields.order_no = data.order_no || '';
            editFormFields.product_name = data.product_name || '';
            editFormFields.Num = Number(data.Num || 0);
            editFormFields.Address = data.Address || '';
            editFormFields.unit_price = Number(data.unit_price || 0);
            editFormFields.total_amount = data.total_amount != null ? Number(data.total_amount) : Number((Number(data.unit_price||0)*Number(data.Num||0)).toFixed(2));
        };
        window.addEventListener('open_shipment_with_order', handler, { once: true });
    }
    
    // 生成发货编号
    const generateShipmentNo = async () => {
        // 本地生成备用方案
        const genLocalNo = () => {
            const d = new Date();
            const yyyy = d.getFullYear();
            const pad = n => (n < 10 ? '0' : '') + n;
            const mm = pad(d.getMonth() + 1);
            const dd = pad(d.getDate());
            const rand = Math.floor(Math.random() * 9000) + 1000;
            return `FH${yyyy}${mm}${dd}${rand}`;
        };
        try {
            console.log('开始生成发货编号...');
            const res = await proxy.http.get('/api/shipment/generateShipmentNo');
            console.log('发货编号生成响应:', res);
            if (res && res.status && res.data) {
                editFormFields.shipment_no = res.data;
                console.log('发货编号已生成:', res.data);
            } else {
                const local = genLocalNo();
                editFormFields.shipment_no = local;
                console.warn('生成发货编号失败，使用本地编号:', local);
            }
        } catch (error) {
            const local = genLocalNo();
            editFormFields.shipment_no = local;
            console.error('生成发货编号异常，使用本地编号:', local, error);
        }
    }
    //监听表单输入，做实时计算
    //watch(() => editFormFields.字段,(newValue, oldValue) => {    })
    // 监听订单编号变化，自动填充商品名称、下单数量和地址
    watch(() => editFormFields.order_no, (newVal, oldVal) => {
        console.log('订单编号变化:', newVal, '(类型:', typeof newVal, ') 旧值:', oldVal);
        console.log('当前订单列表数据:', orderListData.value);
        console.log('订单列表长度:', orderListData.value.length);
        
        if (orderListData.value.length > 0) {
            console.log('第一条订单的ordernoas:', orderListData.value[0].ordernoas);
            console.log('所有订单的ordernoas:', orderListData.value.map(o => o.ordernoas));
        }
        
        if (!newVal) {
            // 如果订单编号清空，则清空关联字段
            editFormFields.product_name = '';
            editFormFields.Num = '';
            editFormFields.Address = '';
            editFormFields.unit_price = '';
            editFormFields.total_amount = '';
            return;
        }
        
        // 从本地保存的订单数据中查找对应的订单
        // 兼容处理：如果newVal是数字，可能是数组索引，也尝试转换为字符串匹配
        let order = orderListData.value.find(o => o.ordernoas === newVal);
        
        // 如果没找到且newVal是数字，尝试用索引查找
        if (!order && typeof newVal === 'number' && newVal >= 0 && newVal < orderListData.value.length) {
            console.log('尝试用索引查找:', newVal);
            order = orderListData.value[newVal];
        }
        
        // 如果还是没找到，尝试转换类型后匹配
        if (!order) {
            order = orderListData.value.find(o => String(o.ordernoas) === String(newVal));
        }
        
        console.log('查找订单编号:', newVal, '(类型:', typeof newVal, ')');
        console.log('找到的订单:', order);
        
        if (order) {
            console.log('找到订单，准备填充数据...');
            console.log('订单完整数据:', order);
            console.log('order.order_name:', order.order_name, '(类型:', typeof order.order_name, ')');
            console.log('order.Num:', order.Num, '(类型:', typeof order.Num, ')');
            console.log('order.shipping_address:', order.shipping_address, '(类型:', typeof order.shipping_address, ')');
            console.log('order.unit_price:', order.unit_price, '(类型:', typeof order.unit_price, ')');
            console.log('order.total_amount:', order.total_amount, '(类型:', typeof order.total_amount, ')');
            
            // 自动填充商品名称、下单数量、地址、单价和总金额（不填充发货编号和货运公司）
            editFormFields.product_name = order.order_name || '';
            editFormFields.Num = Number(order.Num || 0);
            editFormFields.Address = order.shipping_address || '';
            editFormFields.unit_price = Number(order.unit_price || 0);
            // 如果后端没返回总金额，就按单价×数量计算
            const ta = order.total_amount != null ? Number(order.total_amount) : Number((Number(order.unit_price || 0) * Number(order.Num || 0)).toFixed(2));
            editFormFields.total_amount = ta;
            
            console.log('★★★ 关键字段检查 ★★★');
            console.log('原始 order.unit_price:', order.unit_price);
            console.log('转换后 editFormFields.unit_price:', editFormFields.unit_price);
            console.log('原始 order.total_amount:', order.total_amount);
            console.log('计算后 editFormFields.total_amount:', editFormFields.total_amount);
            
            console.log('填充后的表单数据:', {
                product_name: editFormFields.product_name,
                Num: editFormFields.Num,
                Address: editFormFields.Address,
                unit_price: editFormFields.unit_price,
                total_amount: editFormFields.total_amount
            });
            
            // 强制触发视图更新
            setTimeout(() => {
                console.log('延迟检查表单值:', {
                    product_name: editFormFields.product_name,
                    Num: editFormFields.Num,
                    Address: editFormFields.Address,
                    unit_price: editFormFields.unit_price,
                    total_amount: editFormFields.total_amount
                });
            }, 100);
        } else {
            console.warn('未找到订单编号为', newVal, '的订单');
            // 如果没找到订单，清空关联字段（不清空发货编号和货运公司）
            editFormFields.product_name = '';
            editFormFields.Num = '';
            editFormFields.Address = '';
            editFormFields.unit_price = '';
            editFormFields.total_amount = '';
        }
    })
    //对外暴露数据
    defineExpose({})
</script>
<style lang="less" scoped>
</style>
